package com.learn.kotlinlearndemolist.listview

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatImageView
import com.learn.kotlinlearndemolist.model.Fruit
import com.learn.kotlinlearndemolist.R

class FruitListAdapter(activity: AppCompatActivity, private val resourceId: Int, data: MutableList<Fruit>) :
    ArrayAdapter<Fruit>(activity, resourceId, data) {
    inner class ViewHolder(val fruitImg: ImageView, val fruitName: TextView)

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val view: View
        val viewHolder: ViewHolder
        if (convertView == null) {
            view = LayoutInflater.from(context).inflate(resourceId, parent, false)
            val fruitImage: AppCompatImageView = view.findViewById(R.id.fruit_img)
            val fruitName: TextView = view.findViewById(R.id.fruit_name)
            viewHolder = ViewHolder(fruitImage, fruitName)
            view.tag = viewHolder
        } else {
            view = convertView
            viewHolder = view.tag as ViewHolder
        }
        val fruit = getItem(position)
        fruit?.apply {
            viewHolder.fruitImg.setImageResource(fruit.id)
            viewHolder.fruitName.text = fruit.name
        }
        return view
    }
}